//
// Created by hsj on 2022/1/5.
//
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include "t_fstream.h"

using namespace std;

const int SIZE = 60;
const string FILE_NAME= "carinfo.txt";

//测试文件IO操作
//测试文件IO操作
void test_fstream(){
//    test_fstream_out();
    test_fstream_in();
}
void test_fstream_out(){


    char automobile[50];
    int year;
    double a_price;
    double d_price;

    ofstream out_file;
    out_file.open(FILE_NAME);//文件位于build目录，也就是EXE可执行文件目录。默认是覆盖的方式

    cout<<"Enter the make  and model of automobile:";
    cin.getline(automobile,50);

    cout<<"Enter year:";
    cin>>year;
    cout<<"Enter the original ask price:";
    cin>>a_price;
    d_price = a_price * 0.913;

    //输出的精度2位小数
    cout<<fixed;
    cout.precision(2);
    cout.setf(ios_base::showpoint);
    cout<<"Make and model:"<<automobile<<endl;
    cout<<"Year:"<<year<<endl;
    cout<<"Was asking $:"<<a_price<<endl;
    cout<<"Now asking $:"<<d_price<<endl;

    //now out to file
    out_file<<fixed;
    out_file.precision(2);
    out_file.setf(ios_base::showpoint);
    out_file<<"Make and model:"<<automobile<<endl;
    out_file<<"Year:"<<year<<endl;
    out_file<<"Was asking $:"<<a_price<<endl;
    out_file<<"Now asking $:"<<d_price<<endl;

    out_file.close();

}
void test_fstream_in(){


    char line[SIZE];
    ifstream in_file;
    in_file.open(FILE_NAME);
    if (!in_file.is_open()){
        cout<<"notice here!file not exsist!,we will terminate programm"<<endl;
        exit(EXIT_FAILURE);
    }

    while (in_file.getline(line,SIZE) && in_file.good()){//back ifstream,with while input good and not EOF
        cout<<"read a line text:"<<line<<endl;
    }

    if (in_file.eof()){//file EOF
        cout<<"read file complete."<<endl;
    }

    in_file.close();

}